package io.zjw.testblelib

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.nfc.Tag
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.Toast
import cn.jesse.nativelogger.NLogger
import cn.jesse.nativelogger.NLoggerConfig
import cn.jesse.nativelogger.logger.LoggerLevel
import com.alibaba.fastjson.JSONObject
import io.mega.megablelib.MegaBleClient
import io.zjw.testblelib.util.HttpUtil
import kotlinx.android.synthetic.main.activity_index.*
import kotlinx.android.synthetic.main.activity_index.tv_version
import kotlinx.android.synthetic.main.activity_main.*
import java.util.logging.SimpleFormatter
import kotlin.concurrent.thread

class IndexActivity : AppCompatActivity(), View.OnClickListener {


    private lateinit var infoDialog: AlertDialog

    companion object {
        var serverIP = ""
        var userName = ""
        var phoneNumber = ""
        //环境配置：ZB KJB分别在心电和脉搏又特殊处理
//        var env = "ZB"
//        var env = "KJB"
//        var env = ""//群体
        var env = "ccy"//柴春阳--生理信息（心电+脉搏）
//        var env = "TEST"
        var ID = ""
        private const val TAG = "IndexActivity"
        private const val REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124

    }
    // permission checker
    private var mRequestPermissionHandler: RequestPermissionHandler? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_index)
        btn_pluse.setOnClickListener(this)
        btn_ecg.setOnClickListener(this)
        btn_auto_setup_server.setOnClickListener(this)
        btn_eeg.setOnClickListener(this)
        iv_index_info.setOnClickListener(this)

        userName = ""
        phoneNumber = ""
        ID = ""
        mRequestPermissionHandler = RequestPermissionHandler()
        setSupportActionBar(toolbarIndex)
        checkAppPermission()
        scanServerIp()
        Log.d(TAG,"env========$env")
        if(env == "KJB"){
            btn_pluse.visibility = View.VISIBLE
            btn_ecg.visibility = View.INVISIBLE
            btn_eeg.visibility = View.INVISIBLE
        }else if(env == "ZB"){
            btn_pluse.visibility= View.INVISIBLE
            btn_ecg.visibility=View.VISIBLE
        }else if (env == "ccy"){
            btn_pluse.visibility = View.VISIBLE
            btn_ecg.visibility = View.VISIBLE
        }else{
            btn_pluse.visibility= View.VISIBLE
            btn_ecg.visibility=View.VISIBLE
            btn_pluse.isEnabled=true
            btn_ecg.isEnabled=true
            btn_eeg.visibility=View.INVISIBLE
        }
        //连接指定WiFi
//        connectWifi()

        Log.d(TAG,"env========$env==${btn_pluse.visibility}==${btn_eeg.visibility}===${btn_ecg.visibility}")
        NLoggerConfig.init(this)
        NLoggerConfig.getInstance()
                .builder()
                .tag("APP")
                .loggerLevel(LoggerLevel.DEBUG)
                .fileLogger(true)
                .fileDirectory(applicationContext.filesDir.path + "/logs")
                .fileFormatter(SimpleFormatter())
                .expiredPeriod(3)
                .catchException(true) { _, ex ->
                    NLogger.e("uncaughtException", ex!!)
                    android.os.Process.killProcess(android.os.Process.myPid())
                }.build()
        /*NLogger.zipLogs { succeed, target ->
            if (succeed) {
                NLogger.i("zip", "succeed : $target Thread: ${Thread.currentThread().name}")
            }
        }*/
    }

    // connect specified wifi
    private fun connectWifi() {
        val wifiService = applicationContext.getSystemService(Context.WIFI_SERVICE);

    }

    override fun onClick(v: View) {
        var  msg = Message()
        msg.what=1
        when(v.id){

            //脉诊模式
            R.id.btn_pluse -> {
                if (serverIP.isEmpty()) {
                    msg.obj = "未获取到服务器，请刷新服务器或联系管理员。"
                    handler.handleMessage(msg)
                    //Toast.makeText(this,"未获取到服务器，请刷新服务器或联系管理员。",Toast.LENGTH_SHORT).show()
                } else {

                    checkUser(MainActivity::class.java)
//                    Thread.sleep(700)
                }
            }
            //心电模式
            R.id.btn_ecg -> {
                if (serverIP.isEmpty()) {
                    msg.obj = "未获取到服务器，请刷新服务器或联系管理员。"
                    handler.handleMessage(msg)
                    //Toast.makeText(this,"未获取到服务器，请刷新服务器或联系管理员。",Toast.LENGTH_SHORT).show()
                } else {
                    checkUser(EcgActivity::class.java)

//                    if (userName.isNotEmpty()) {
//                        startActivity(Intent(this, EcgActivity::class.java).putExtra("serverIP", serverIP)
//                                .putExtra("userName", userName)
//                                .putExtra("phoneNumber", phoneNumber))
//                    }
                }
            }
            //脑电模式
            R.id.btn_eeg -> {
                if(serverIP.isEmpty()){
                    msg.obj = "未获取到服务器，请刷新服务器或联系管理员。"
                    handler.handleMessage(msg)
                }else{
                    checkUser(EEGActivity::class.java)
                }
            }
            R.id.iv_index_info -> {
                try {
                    val versionName = packageManager.getPackageInfo(this.packageName, 0).versionName
                    tv_version.text = "v$versionName"
                    var message = String.format(getString(R.string.info_content), versionName, MegaBleClient.megaParseVesrion(), serverIP)
                    infoDialog = AlertDialog.Builder(this)
                            .setTitle(R.string.info_title)
                            .setPositiveButton(R.string.ok, null)
                            .setMessage(message)
                            .create()
                    infoDialog.show()
                } catch (e: PackageManager.NameNotFoundException) {
                    e.printStackTrace()
                }
            }
            R.id.btn_auto_setup_server -> {
                thread {
                    kotlin.run {
                        ServerUtil.changeOpenState(this)
                        val str = ServerUtil.setUpServer(this, env)
                        if (str.trim().isEmpty()) {
                            Looper.prepare()
                            infoDialog = AlertDialog.Builder(this)
                                    .setTitle("错误：")
                                    .setPositiveButton(R.string.ok, null)
                                    .setMessage("连接服务器超时请联系管理员")
                                    .create()
                            infoDialog.show()
                            Looper.loop()
                        } else {
                            serverIP = str;

                            msg.obj = "服务器连接成功"
                            handler.sendMessage(msg)
                        }
                    }
                }
            }
        }
    }
    //权限验证   蓝牙、位置
    private fun checkAppPermission() {
        mRequestPermissionHandler!!.requestPermission(this, arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.BLUETOOTH_ADMIN
        ), REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS, object : RequestPermissionHandler.RequestPermissionListener {
            override fun onSuccess() {
                // Toast.makeText(MainActivity.this, "request permission success", Toast.LENGTH_SHORT).show();
            }

            override fun onFailed() {
                Toast.makeText(this@IndexActivity, "request permission failed", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun scanServerIp(){
        Log.d(TAG,"scanServerIp====")
        serverIP = getSharedPreferences("save.himi", Context.MODE_PRIVATE).getString("SERVER_IP", "")
        Log.d(TAG, "ServerIp====$serverIP")
//        Toast.makeText(this, "开始连接服务器", Toast.LENGTH_SHORT)
        if(serverIP.trim().isEmpty()){
            thread {
                Log.d(TAG,"thread")
                kotlin.run {
                    val str = ServerUtil.setUpServer(this, env);
                    Log.d(TAG,"thread1")
                    if(str==null ||str.trim().isEmpty()){
                        Log.d(TAG,"thread2")
                        Looper.prepare()
                        infoDialog = AlertDialog.Builder(this)
                                .setTitle("错误：")
                                .setPositiveButton(R.string.ok, null)
                                .setMessage("连接服务器超时请联系管理员")
                                .create()
                        infoDialog.show()
                        Looper.loop()
                    }else{
                        Log.d(TAG,"thread3")
                        serverIP = str

                        var  msg = Message()
                        msg.what=1

                        msg.obj = "连接服务器成功"
//                        handler.handleMessage(msg)
                        handler.sendMessage(msg)

                    }
                }
            }
        }else{
            Log.d(TAG,"thread4")
            var  msg = Message()
            msg.what=1
//            val url = "http://"+serverIP+":8081"
                //Toast.makeText(this,"连接服务器成功",Toast.LENGTH_SHORT).show()
                msg.obj = "连接服务器成功"
                handler.handleMessage(msg)
        }
    }

    private fun checkUser(flag: Class<*>){
        //保存数据，输入用户信息
        val builder = AlertDialog.Builder(this)
        val editTextUserName = EditText(this)
//        editTextUserName.inputType = EditorInfo.TYPE_CLASS_PHONE
        editTextUserName.inputType = EditorInfo.TYPE_CLASS_TEXT
//        editTextUserName.setFilters(arrayOf<InputFilter>(InputFilter.LengthFilter(11))) //设置限制长度，多了输入不了
//        editTextUserName.setText(phoneNumber)
        builder.setView(editTextUserName)
//        builder.setTitle("请输入您的手机号")
        builder.setTitle("请输入账号")
        builder.setPositiveButton("确定") { dialog, which ->
            phoneNumber = editTextUserName.text.toString()
            //验证用户信息
            if(phoneNumber.trim().isEmpty()){
               /* var  msg = Message()
                msg.what=1
//            val url = "http://"+serverIP+":8081"
                //Toast.makeText(this,"连接服务器成功",Toast.LENGTH_SHORT).show()
                msg.obj = "请填写信息"
                handler.handleMessage(msg)*/
                Toast.makeText(this@IndexActivity,"请填写信息",Toast.LENGTH_SHORT).show()
                return@setPositiveButton
            }
            var port = 8082;
            if (env == "ZB"){
                port = 8081
            }else if(env == "KJB"){
                port = 8086
            }else if (env == "ccy"){
                port = 8109
            }
            var url = "http://$serverIP:$port/user/$phoneNumber/checkUser"
            if(env=="KJB"){
                url = "http://$serverIP:$port/v1/user/$phoneNumber/checkUser"
            }
            if (env == "TEST"){
                url = "http://$serverIP:8086/v1/user/$phoneNumber/checkUser"
            }
            Log.i(TAG, "url--$url")
            Thread {
                try {
                    if(env != "TEST"){
                        Log.i("httpUtil", HttpUtil.httpGet(url))
                        var responseStr = HttpUtil.httpGet(url)
                        userName = ""
                        ID = ""
                        if(responseStr.isNotEmpty()){
                            Log.i(TAG,responseStr)
                            try {
                                val jsonObject =  JSONObject.parseObject(responseStr)
                                userName = jsonObject.getString("userName")
                                ID = jsonObject.getString("ID")
                            }catch ( exe: java.lang.Exception){
                                exe.printStackTrace()
                            }

                        }
                    }else{
                        userName = "张三"
                        ID = "ZhangSan's ID"
                    }
//
                    println("userName---$userName")
                    if (userName.isEmpty()) {
                        Looper.prepare();
                        infoDialog = AlertDialog.Builder(this)
                                .setTitle("错误：")
                                .setPositiveButton(R.string.ok, null)
                                .setMessage("请先注册！")
                                .create()
                        infoDialog.show()
                        Looper.loop()

                    }else{
                        startActivity(Intent(this, flag).putExtra("serverIP", serverIP)
                                .putExtra("userName", userName)
                                .putExtra("phoneNumber", phoneNumber)
                                .putExtra("ID",ID)
                                .putExtra("env",env))
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
            }.start()
        }
        builder.show()
    }


    private var handler:Handler = object :Handler(){
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when(msg?.what){
                1 -> {
                    var toast = Toast.makeText(this@IndexActivity, msg.obj.toString(), Toast.LENGTH_SHORT)

                    if(env =="KJB"){
                        btn_pluse.isEnabled = true
                    }else{
                        btn_pluse.isEnabled = true
                        btn_ecg.isEnabled = true
                    }

//                    btn_eeg.isEnabled = true
                    toast.setGravity(Gravity.TOP, 0, 0)
                    toast.show()
                }
                2 -> {
                    var toast = Toast.makeText(this@IndexActivity, msg.obj.toString(), Toast.LENGTH_SHORT)
                    btn_pluse.isEnabled = true
                    btn_ecg.isEnabled = true
//                    btn_eeg.isEnabled = true
                    toast.setGravity(Gravity.BOTTOM, 0, 0)
                    toast.show()
                }
            }
        }
    }
}
